<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#fff">



  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">




  
  
    
      
    
    
      
    
  <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
  <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-flash.min.css" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />





  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "b3c7d22e"
    });
  daovoice('update');
  </script>








  <meta name="baidu-site-verification" content="true" />







  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.1" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1">


  <link rel="icon" type="image/png" sizes="32x32" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1">


  <link rel="icon" type="image/png" sizes="16x16" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1">


  <link rel="mask-icon" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1" color="#fff">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '6.4.1',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":true,"transition":{"post_block":"perspectiveLeftIn","post_header":"fadeIn","post_body":"fadeIn","coll_header":"perspectiveLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键字","hits_empty":"没有找到与 ${query} 相关的内容","hits_stats":"${hits}条相关记录，共耗时${time} ms"}
    }
  };
</script>


  



<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://yfzhou.coding.me/"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>

  <meta name="description" content="JUC中ConcurrentSkipListMap线程安全并发容器了解下？">
<meta name="keywords" content="java,JUC,ConcurrentSkipListMap">
<meta property="og:type" content="article">
<meta property="og:title" content="剑指ConcurrentSkipListMap">
<meta property="og:url" content="https://yfzhou.coding.me/2019/01/17/剑指ConcurrentSkipListMap/index.html">
<meta property="og:site_name" content="Felix">
<meta property="og:description" content="JUC中ConcurrentSkipListMap线程安全并发容器了解下？">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/%E8%B7%B3%E8%A1%A8.jpg">
<meta property="og:image" content="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/Skip_list_add_element-en.gif">
<meta property="og:image" content="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/ConcurrentSkipListMap.jpg">
<meta property="og:image" content="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/TIM%E6%88%AA%E5%9B%BE20190117111543.png">
<meta property="og:updated_time" content="2019-04-17T08:59:25.165Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="剑指ConcurrentSkipListMap">
<meta name="twitter:description" content="JUC中ConcurrentSkipListMap线程安全并发容器了解下？">
<meta name="twitter:image" content="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/%E8%B7%B3%E8%A1%A8.jpg">



  <link rel="alternate" href="/atom.xml" title="Felix" type="application/atom+xml" />




  <link rel="canonical" href="https://yfzhou.coding.me/2019/01/17/剑指ConcurrentSkipListMap/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>剑指ConcurrentSkipListMap | Felix</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Felix</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">Viva La Vida</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-top">
    <a href="/top/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-signal"></i> <br />TopX</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-sitemap">
    <a href="/sitemap.xml" rel="section">
      <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />站点地图</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="输入关键字搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://yfzhou.coding.me/2019/01/17/剑指ConcurrentSkipListMap/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Felix">
      <meta itemprop="description" content="周宇峰的博客">
      <meta itemprop="image" content="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/user_head_img.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Felix">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">剑指ConcurrentSkipListMap
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-01-17 15:15:52" itemprop="dateCreated datePublished" datetime="2019-01-17T15:15:52+08:00">2019-01-17</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-04-17 16:59:25" itemprop="dateModified" datetime="2019-04-17T16:59:25+08:00">2019-04-17</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/java/" itemprop="url" rel="index"><span itemprop="name">java</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/01/17/剑指ConcurrentSkipListMap/" class="leancloud_visitors" data-flag-title="剑指ConcurrentSkipListMap">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-edit"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">20k</span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">24 分钟</span>
              
            </div>
          

          
              <div class="post-description">JUC中ConcurrentSkipListMap线程安全并发容器了解下？</div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><span></span></p>
<a id="more"></a>
<p>上一篇文章给大家详细介绍了下跳表的概念，还不清楚的小伙伴可以去看看，<a href="https://542869246.github.io/2019/01/14/%E8%B7%B3%E8%A1%A8-SkipList-%E4%BA%86%E8%A7%A3%E4%B8%8B%EF%BC%9F/" target="_blank" rel="noopener">跳表(SkipList)了解下？</a></p>
<h2 id="回顾"><a href="#回顾" class="headerlink" title="回顾"></a>回顾</h2><p>这里再贴下跳表结构图以及插入节点的GIF图，大家再眼熟下：<br><img src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/%E8%B7%B3%E8%A1%A8.jpg" alt=""></p>
<p><img src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/Skip_list_add_element-en.gif" alt=""></p>
<p>通过之前的学习，我们知道跳表采用空间换时间的算法，他的插入和查找的效率O(logn)，效率不低于红黑树，但是其原理和实现的复杂度要比红黑树简单多了。一般来说会操作链表List，就会对SkipList毫无压力。</p>
<h2 id="ConcurrentSkipListMap数据结构"><a href="#ConcurrentSkipListMap数据结构" class="headerlink" title="ConcurrentSkipListMap数据结构"></a>ConcurrentSkipListMap数据结构</h2><p>从名字就可以猜到，ConcurrentSkipListMap的数据结构使用的是跳表，看下ConcurrentSkipListMap的数据结构图：<br><img src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/ConcurrentSkipListMap.jpg" alt=""></p>
<p>其实ConcurrentSkipListMap头部注解也画了个图：<br><img src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/TIM%E6%88%AA%E5%9B%BE20190117111543.png" alt=""></p>
<h2 id="重要的内部类"><a href="#重要的内部类" class="headerlink" title="重要的内部类"></a>重要的内部类</h2><p>ConcurrentSkipListMap包含了很多内部类，下面我们介绍3个重要的内部类：Index、HeadIndex、Node。</p>
<p>其实看上面的数据结构图就知道了这三个内部类主要是干嘛的了</p>
<h3 id="Index"><a href="#Index" class="headerlink" title="Index"></a>Index</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Index</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> Node&lt;K,V&gt; node;</span><br><span class="line">    <span class="keyword">final</span> Index&lt;K,V&gt; down;</span><br><span class="line">    <span class="keyword">volatile</span> Index&lt;K,V&gt; right;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Unsafe mechanics</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> sun.misc.Unsafe UNSAFE;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> rightOffset;</span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            UNSAFE = sun.misc.Unsafe.getUnsafe();</span><br><span class="line">            Class&lt;?&gt; k = Index.class;</span><br><span class="line">            rightOffset = UNSAFE.objectFieldOffset</span><br><span class="line">                (k.getDeclaredField(<span class="string">"right"</span>));</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> Error(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	...		</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看到，Index节点包括一个Node节点的引用、一个指向下层的down域和一个指向下一个Index的right域，即对应数据结构中的Index节点。sun.misc.Unsafe这个包熟悉吧？CAS嘛，不清楚的同学可以去看看我写的 <a href="https://542869246.github.io/2018/12/17/CAS%E6%9C%BA%E5%88%B6%E6%98%AF%E4%BB%80%E4%B9%88%E9%AC%BC%EF%BC%9F/" target="_blank" rel="noopener">CAS机制是什么鬼？</a> 修改right域的时候确保原子性。</p>
<h3 id="HeadIndex"><a href="#HeadIndex" class="headerlink" title="HeadIndex"></a>HeadIndex</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Nodes heading each level keep track of their level.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">HeadIndex</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt; <span class="keyword">extends</span> <span class="title">Index</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> level;</span><br><span class="line">    HeadIndex(Node&lt;K,V&gt; node, Index&lt;K,V&gt; down, Index&lt;K,V&gt; right, <span class="keyword">int</span> level) &#123;</span><br><span class="line">        <span class="keyword">super</span>(node, down, right);</span><br><span class="line">        <span class="keyword">this</span>.level = level;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>配合数据结构图可以知道，HeadIndex主要是表示当前层级的，继承自Index类，并且在Index类的基础上添加了level域。</p>
<h3 id="Node"><a href="#Node" class="headerlink" title="Node"></a>Node</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt; </span>&#123;</span><br><span class="line">        <span class="comment">// 键</span></span><br><span class="line">        <span class="keyword">final</span> K key;</span><br><span class="line">        <span class="comment">// 值</span></span><br><span class="line">        <span class="keyword">volatile</span> Object value;</span><br><span class="line">        <span class="comment">// 下一个节点</span></span><br><span class="line">        <span class="keyword">volatile</span> Node&lt;K,V&gt; next;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// UNSAFE mechanics</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> sun.misc.Unsafe UNSAFE;</span><br><span class="line">        <span class="comment">// value域的偏移地址</span></span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> valueOffset;</span><br><span class="line">        <span class="comment">// next域的偏移地址</span></span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> nextOffset;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">static</span> &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                UNSAFE = sun.misc.Unsafe.getUnsafe();</span><br><span class="line">                Class&lt;?&gt; k = Node.class;</span><br><span class="line">                valueOffset = UNSAFE.objectFieldOffset</span><br><span class="line">                    (k.getDeclaredField(<span class="string">"value"</span>));</span><br><span class="line">                nextOffset = UNSAFE.objectFieldOffset</span><br><span class="line">                    (k.getDeclaredField(<span class="string">"next"</span>));</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> Error(e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>Node就是存放原始数据的节点了，包含了key、value、next域，链表结构，同样使用CAS确保修改value和next的原子性。</p>
<h2 id="属性"><a href="#属性" class="headerlink" title="属性"></a>属性</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ConcurrentSkipListMap</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt; <span class="keyword">extends</span> <span class="title">AbstractMap</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt;</span></span><br><span class="line"><span class="class">    <span class="keyword">implements</span> <span class="title">ConcurrentNavigableMap</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt;, <span class="title">Cloneable</span>, <span class="title">Serializable</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 版本序列号    </span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = -<span class="number">8627078645895051609L</span>;</span><br><span class="line">    <span class="comment">// 基础层的头节点</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Object BASE_HEADER = <span class="keyword">new</span> Object();</span><br><span class="line">    <span class="comment">// 最顶层头节点的索引</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">transient</span> <span class="keyword">volatile</span> HeadIndex&lt;K,V&gt; head;</span><br><span class="line">    <span class="comment">// 比较器</span></span><br><span class="line">    <span class="keyword">final</span> Comparator&lt;? <span class="keyword">super</span> K&gt; comparator;</span><br><span class="line">    <span class="comment">// 键集合</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">transient</span> KeySet&lt;K&gt; keySet;</span><br><span class="line">    <span class="comment">// entry集合</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">transient</span> EntrySet&lt;K,V&gt; entrySet;</span><br><span class="line">    <span class="comment">// 值集合</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">transient</span> Values&lt;V&gt; values;</span><br><span class="line">    <span class="comment">// 降序键集合</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">transient</span> ConcurrentNavigableMap&lt;K,V&gt; descendingMap;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// Unsafe mechanics</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> sun.misc.Unsafe UNSAFE;</span><br><span class="line">    <span class="comment">// head域的偏移量</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> headOffset;</span><br><span class="line">    <span class="comment">// Thread类的threadLocalRandomSecondarySeed的偏移量</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> SECONDARY;</span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            UNSAFE = sun.misc.Unsafe.getUnsafe();</span><br><span class="line">            Class&lt;?&gt; k = ConcurrentSkipListMap.class;</span><br><span class="line">            headOffset = UNSAFE.objectFieldOffset</span><br><span class="line">                (k.getDeclaredField(<span class="string">"head"</span>));</span><br><span class="line">            Class&lt;?&gt; tk = Thread.class;</span><br><span class="line">            SECONDARY = UNSAFE.objectFieldOffset</span><br><span class="line">                (tk.getDeclaredField(<span class="string">"threadLocalRandomSecondarySeed"</span>));</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> Error(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="构造函数"><a href="#构造函数" class="headerlink" title="构造函数"></a>构造函数</h2><p>四个构造函数<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Constructs a new, empty map, sorted according to the</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@linkplain</span> Comparable natural ordering&#125; of the keys.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ConcurrentSkipListMap</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.comparator = <span class="keyword">null</span>;</span><br><span class="line">    initialize();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Constructs a new, empty map, sorted according to the specified</span></span><br><span class="line"><span class="comment"> * comparator.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> comparator the comparator that will be used to order this map.</span></span><br><span class="line"><span class="comment"> *        If &#123;<span class="doctag">@code</span> null&#125;, the &#123;<span class="doctag">@linkplain</span> Comparable natural</span></span><br><span class="line"><span class="comment"> *        ordering&#125; of the keys will be used.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ConcurrentSkipListMap</span><span class="params">(Comparator&lt;? <span class="keyword">super</span> K&gt; comparator)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.comparator = comparator;</span><br><span class="line">    initialize();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Constructs a new map containing the same mappings as the given map,</span></span><br><span class="line"><span class="comment"> * sorted according to the &#123;<span class="doctag">@linkplain</span> Comparable natural ordering&#125; of</span></span><br><span class="line"><span class="comment"> * the keys.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span>  m the map whose mappings are to be placed in this map</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> ClassCastException if the keys in &#123;<span class="doctag">@code</span> m&#125; are not</span></span><br><span class="line"><span class="comment"> *         &#123;<span class="doctag">@link</span> Comparable&#125;, or are not mutually comparable</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> NullPointerException if the specified map or any of its keys</span></span><br><span class="line"><span class="comment"> *         or values are null</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ConcurrentSkipListMap</span><span class="params">(Map&lt;? extends K, ? extends V&gt; m)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.comparator = <span class="keyword">null</span>;</span><br><span class="line">    initialize();</span><br><span class="line">    putAll(m);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Constructs a new map containing the same mappings and using the</span></span><br><span class="line"><span class="comment"> * same ordering as the specified sorted map.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> m the sorted map whose mappings are to be placed in this</span></span><br><span class="line"><span class="comment"> *        map, and whose comparator is to be used to sort this map</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> NullPointerException if the specified sorted map or any of</span></span><br><span class="line"><span class="comment"> *         its keys or values are null</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ConcurrentSkipListMap</span><span class="params">(SortedMap&lt;K, ? extends V&gt; m)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.comparator = m.comparator();</span><br><span class="line">    initialize();</span><br><span class="line">    buildFromSorted(m);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>可以看到都调用了initialize()方法，进行初始化工作。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initialize</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    keySet = <span class="keyword">null</span>;</span><br><span class="line">    entrySet = <span class="keyword">null</span>;</span><br><span class="line">    values = <span class="keyword">null</span>;</span><br><span class="line">    descendingMap = <span class="keyword">null</span>;</span><br><span class="line">    head = <span class="keyword">new</span> HeadIndex&lt;K,V&gt;(<span class="keyword">new</span> Node&lt;K,V&gt;(<span class="keyword">null</span>, BASE_HEADER, <span class="keyword">null</span>),</span><br><span class="line">                              <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="number">1</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="put操作"><a href="#put操作" class="headerlink" title="put操作"></a>put操作</h2><p>简单判断下非空，然后执行doPut()函数，看过JDK源码的应该很熟悉这种操作了。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> V <span class="title">put</span><span class="params">(K key, V value)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (value == <span class="keyword">null</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">    <span class="keyword">return</span> doPut(key, value, <span class="keyword">false</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>doPut()源码很多，咋们拆开来看。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> V <span class="title">doPut</span><span class="params">(K key, V value, <span class="keyword">boolean</span> onlyIfAbsent)</span> </span>&#123;</span><br><span class="line">    Node&lt;K,V&gt; z;             <span class="comment">// added node</span></span><br><span class="line">    <span class="keyword">if</span> (key == <span class="keyword">null</span>) <span class="comment">// 键为空，抛出空异常</span></span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">    <span class="comment">// 比较器</span></span><br><span class="line">    Comparator&lt;? <span class="keyword">super</span> K&gt; cmp = comparator;</span><br><span class="line">    <span class="comment">// 死循环，打个标记outer，可通过break outer跳出循环</span></span><br><span class="line">    outer: <span class="keyword">for</span> (;;) &#123; </span><br><span class="line">        <span class="keyword">for</span> (Node&lt;K,V&gt; b = findPredecessor(key, cmp), n = b.next;;) &#123;</span><br><span class="line"></span><br><span class="line">	......</span><br></pre></td></tr></table></figure>
<p>可以看到doPut有三个入参K、V、onlyIfAbsent。KV大家都知道，这个boolean类型的onlyIfAbsent的作用是如果存在当前key时，该做何动作？当onlyIfAbsent为false时，替换value，为true时，则返回该value。</p>
<p>主题其中还调用了findPredecessor()方法，传入key来确认位置，该方法就是确认key插入位置的。<br>findPredecessor()源码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> Node&lt;K,V&gt; <span class="title">findPredecessor</span><span class="params">(Object key, Comparator&lt;? <span class="keyword">super</span> K&gt; cmp)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (key == <span class="keyword">null</span>) <span class="comment">// 键为空，抛出空异常</span></span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException(); <span class="comment">// don't postpone errors</span></span><br><span class="line">    <span class="keyword">for</span> (;;) &#123; <span class="comment">//死循环</span></span><br><span class="line">        <span class="comment">// 从head节点开始，head是level最高级别的headIndex</span></span><br><span class="line">        <span class="keyword">for</span> (Index&lt;K,V&gt; q = head, r = q.right, d;;) &#123;</span><br><span class="line">            <span class="comment">// r != null，表示该节点右边还有节点，需要比较</span></span><br><span class="line">            <span class="keyword">if</span> (r != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">// n为当前Node节点</span></span><br><span class="line">                Node&lt;K,V&gt; n = r.node;</span><br><span class="line">                <span class="comment">// 为当前key</span></span><br><span class="line">                K k = n.key;</span><br><span class="line">                <span class="comment">// value == null，表示该节点已经被删除了</span></span><br><span class="line">                <span class="keyword">if</span> (n.value == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="comment">// 通过unlink()方法过滤掉该节点</span></span><br><span class="line">                    <span class="keyword">if</span> (!q.unlink(r))</span><br><span class="line">                        <span class="keyword">break</span>;           <span class="comment">// restart</span></span><br><span class="line">                    <span class="comment">// r为rightIndex节点</span></span><br><span class="line">                    r = q.right;         <span class="comment">// reread r</span></span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="comment">// value != null，节点存在</span></span><br><span class="line">                <span class="comment">// 如果key 大于r节点的key 则往前进一步</span></span><br><span class="line">                <span class="keyword">if</span> (cpr(cmp, key, k) &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                    <span class="comment">// 向右移动</span></span><br><span class="line">                    q = r;</span><br><span class="line">                    r = r.right;</span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 到达最右边，如果dowm == null，表示指针已经达到最下层了，直接返回q对应的Node节点</span></span><br><span class="line">            <span class="keyword">if</span> ((d = q.down) == <span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">return</span> q.node;</span><br><span class="line">            <span class="comment">// 向下移动</span></span><br><span class="line">            q = d;</span><br><span class="line">            <span class="comment">// d的right节点</span></span><br><span class="line">            r = d.right;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>findPredecessor()方法就是寻找前辈节点。从最高层HeadIndex开始向右一个个比较，直到right域为null或者右边的key大于当前的key，然后通过down域向下寻找，直到down为null，找到后返回原始数据的Node节点。</p>
<p>这个过程中还会执行另一个操作unlink()，判断节点的value是否为null，如果为null，表示该节点已经被删除了，通过调用unlink()方法删除该节点。</p>
<p>OK，现在通过findPredecessor()方法找到前辈节点后，继续走。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 无限循环</span></span><br><span class="line">outer: <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">    <span class="comment">// 找到前辈节点，n为当前节点</span></span><br><span class="line">    <span class="keyword">for</span> (Node&lt;K,V&gt; b = findPredecessor(key, cmp), n = b.next;;) &#123;</span><br><span class="line">        <span class="comment">// 前辈节点的next != null</span></span><br><span class="line">        <span class="keyword">if</span> (n != <span class="keyword">null</span>) &#123;</span><br><span class="line">            Object v; <span class="keyword">int</span> c;</span><br><span class="line">            <span class="comment">// f为当前节点的后继节点</span></span><br><span class="line">            Node&lt;K,V&gt; f = n.next;</span><br><span class="line">            <span class="comment">// 不一致读，主要原因是并发，有节点捷足先登，重试</span></span><br><span class="line">            <span class="keyword">if</span> (n != b.next)               <span class="comment">// inconsistent read</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            / n.value == <span class="keyword">null</span>，该节点已经被删除了</span><br><span class="line">            <span class="keyword">if</span> ((v = n.value) == <span class="keyword">null</span>) &#123;   <span class="comment">// n is deleted</span></span><br><span class="line">                <span class="comment">// 进行删除</span></span><br><span class="line">                n.helpDelete(b, f);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 前辈节点b已经被删除</span></span><br><span class="line">            <span class="keyword">if</span> (b.value == <span class="keyword">null</span> || v == n) <span class="comment">// b is deleted</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="comment">//  key大于节点的key</span></span><br><span class="line">            <span class="keyword">if</span> ((c = cpr(cmp, key, n.key)) &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">// b往后移动</span></span><br><span class="line">                b = n;</span><br><span class="line">                <span class="comment">// n往后移动</span></span><br><span class="line">                n = f;</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// c == 0 表示，找到一个key相等的节点，根据onlyIfAbsent参数来做判断</span></span><br><span class="line">            <span class="comment">// onlyIfAbsent ==false，则通过casValue，替换value</span></span><br><span class="line">            <span class="comment">// onlyIfAbsent == true，返回该value</span></span><br><span class="line">            <span class="keyword">if</span> (c == <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (onlyIfAbsent || n.casValue(v, value)) &#123;</span><br><span class="line">                    <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>) V vv = (V)v;</span><br><span class="line">                    <span class="keyword">return</span> vv;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">break</span>; <span class="comment">// restart if lost race to replace value</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// else c &lt; 0; fall through</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 将key、value包装成一个node，插入</span></span><br><span class="line">        z = <span class="keyword">new</span> Node&lt;K,V&gt;(key, value, n);</span><br><span class="line">        <span class="keyword">if</span> (!b.casNext(n, z)) <span class="comment">// CAS比较并交换next域</span></span><br><span class="line">            <span class="keyword">break</span>;         <span class="comment">// restart if lost race to append to b</span></span><br><span class="line">        <span class="comment">// 成功，则跳出循环</span></span><br><span class="line">        <span class="keyword">break</span> outer;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>找到前辈节点后，通过以上步骤找到合适的位置插入节点。new一个Node节点通过casNext()方法加入到原始数据Node链表中。</p>
<p>在原始数据插入节点后，还远远不够，毕竟这是跳表，不是链表。还需要新建Index索引，新建Index之前，还需要确认新节点的高度(level)，所以就采用如下方式来生成随机数。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> rnd = ThreadLocalRandom.nextSecondarySeed();</span><br></pre></td></tr></table></figure>
<p>生成随机数之后进行判断，0x80000001这个数字比较特殊，为-2147483647，生成随机数为正偶数才会更新层级（通过最高位和最低位不为1验证）。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> ((rnd &amp; <span class="number">0x80000001</span>) == <span class="number">0</span>) &#123; <span class="comment">// test highest and lowest bits</span></span><br><span class="line">    <span class="keyword">int</span> level = <span class="number">1</span>, max;</span><br><span class="line">    <span class="keyword">while</span> (((rnd &gt;&gt;&gt;= <span class="number">1</span>) &amp; <span class="number">1</span>) != <span class="number">0</span>) <span class="comment">// 判断从右到左有多少个连续的1</span></span><br><span class="line">        ++level;</span><br><span class="line">    Index&lt;K,V&gt; idx = <span class="keyword">null</span>;</span><br><span class="line">  </span><br><span class="line">     ...</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>之后的while循环用来计算跳表的level，level等于从低2位开始向左有多少个连续的1的个数。<br>算出level之后，会有两种情况，一是level高于最高层次的话就需要新增一层，二是小于等于当前最高层次。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// idx:新添加的index的level层index</span></span><br><span class="line">Index&lt;K,V&gt; idx = <span class="keyword">null</span>;</span><br><span class="line"><span class="comment">// 保存头节点</span></span><br><span class="line">HeadIndex&lt;K,V&gt; h = head;</span><br><span class="line"><span class="comment">// 构建Index逻辑</span></span><br><span class="line"><span class="keyword">if</span> (level &lt;= (max = h.level)) &#123; <span class="comment">// 不需要增加层级</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= level; ++i)</span><br><span class="line">        <span class="comment">// 从下到上构建,节点持有新节点z和down节点idx的引用</span></span><br><span class="line">        idx = <span class="keyword">new</span> Index&lt;K,V&gt;(z, idx, <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">else</span> &#123; <span class="comment">// try to grow by one level</span></span><br><span class="line">    <span class="comment">// 构建新层级（旧层级+1）</span></span><br><span class="line">    level = max + <span class="number">1</span>; <span class="comment">// hold in array and later pick the one to use</span></span><br><span class="line">    <span class="comment">// 构建一个level+1长度的Index数组，idxs[0]不作使用</span></span><br><span class="line">    <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)Index&lt;K,V&gt;[] idxs =</span><br><span class="line">        (Index&lt;K,V&gt;[])<span class="keyword">new</span> Index&lt;?,?&gt;[level+<span class="number">1</span>];</span><br><span class="line">    <span class="comment">// 从下到到上构建新的头结点Index，并赋值down域</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= level; ++i)</span><br><span class="line">        idxs[i] = idx = <span class="keyword">new</span> Index&lt;K,V&gt;(z, idx, <span class="keyword">null</span>);</span><br><span class="line">    <span class="comment">// 死循环</span></span><br><span class="line">    <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">        h = head;</span><br><span class="line">        <span class="comment">// 保存跳表之前的层级</span></span><br><span class="line">        <span class="keyword">int</span> oldLevel = h.level;</span><br><span class="line">        <span class="comment">// 层次扩大了，需要重新开始（有新线程节点加入）</span></span><br><span class="line">        <span class="keyword">if</span> (level &lt;= oldLevel) <span class="comment">// lost race to add level</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 保存头结点</span></span><br><span class="line">        HeadIndex&lt;K,V&gt; newh = h;</span><br><span class="line">        <span class="comment">// 保存头结点对应的Node结点</span></span><br><span class="line">        Node&lt;K,V&gt; oldbase = h.node;</span><br><span class="line">        <span class="comment">// 生成新的HeadIndex节点，该HeadIndex指向新增层次</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = oldLevel+<span class="number">1</span>; j &lt;= level; ++j)</span><br><span class="line">            newh = <span class="keyword">new</span> HeadIndex&lt;K,V&gt;(oldbase, newh, idxs[j], j);</span><br><span class="line">        <span class="comment">// CAS比较并替换头结点</span></span><br><span class="line">        <span class="keyword">if</span> (casHead(h, newh)) &#123;</span><br><span class="line">            h = newh;</span><br><span class="line">            <span class="comment">// idx赋值为之前层级的头节点，并将level赋值为之前的层级</span></span><br><span class="line">            idx = idxs[level = oldLevel];</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当level小于等于当前层级，就会从下到上构建，每一层初始化一个Index，该Index的down域指向下一层的节点，right域为null，node直线新插入的Node。<br>当level大于当前层级时，就新增一层。就行以下逻辑操作：<br>1.初始化一个长度为level+1长度的Index数组， 从下到到上构建新的节点Index，并赋值down域right域node域。<br>2.通过一个死循环，从最高层处理，新增一个HeadIndex，该HeadIndex的node域指向之前的最高层的Node，right域指向刚才常见的对应层次的Index，level为当前层次，down域指向前的最高层的HeadIndex。最后通过CAS操作吧当前的head与新加入层的head进行替换。</p>
<p>通过以上步骤，我们已经将Node插入到原始数据链表，确定了level，并且生成了相应的Index以及HeadIndex。现在还差最后一步了，就是把这些Index插入到相对应的层中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// find insertion points and splice in</span></span><br><span class="line"><span class="comment">// 插入Index</span></span><br><span class="line">splice: <span class="keyword">for</span> (<span class="keyword">int</span> insertionLevel = level;;) &#123;</span><br><span class="line">    <span class="comment">// 获取新跳表head的层级</span></span><br><span class="line">    <span class="keyword">int</span> j = h.level;</span><br><span class="line">    <span class="comment">// q:新跳表head; r:q.right; t:新增的Index节点</span></span><br><span class="line">    <span class="keyword">for</span> (Index&lt;K,V&gt; q = h, r = q.right, t = idx;;) &#123;</span><br><span class="line">        <span class="comment">// 头节点或者idx节点为空</span></span><br><span class="line">        <span class="keyword">if</span> (q == <span class="keyword">null</span> || t == <span class="keyword">null</span>)</span><br><span class="line">            <span class="comment">// 跳出外层循环</span></span><br><span class="line">            <span class="keyword">break</span> splice;</span><br><span class="line">        <span class="comment">// right节点不为空</span></span><br><span class="line">        <span class="keyword">if</span> (r != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// 保存r对应的Node节点</span></span><br><span class="line">            Node&lt;K,V&gt; n = r.node;</span><br><span class="line">            <span class="comment">// compare before deletion check avoids needing recheck</span></span><br><span class="line">            <span class="comment">// 比较key与节点的key值</span></span><br><span class="line">            <span class="keyword">int</span> c = cpr(cmp, key, n.key);</span><br><span class="line">            <span class="comment">// 节点的值为空，表示需要删除</span></span><br><span class="line">            <span class="keyword">if</span> (n.value == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">// 删除q的right节点r，并替换为r.right</span></span><br><span class="line">                <span class="keyword">if</span> (!q.unlink(r))</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                <span class="comment">// r为q的right节点</span></span><br><span class="line">                r = q.right;</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// key大于节点的key，向右寻找</span></span><br><span class="line">            <span class="keyword">if</span> (c &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                q = r;</span><br><span class="line">                r = r.right;</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 新跳表head层级等于旧跳表head层级</span></span><br><span class="line">        <span class="keyword">if</span> (j == insertionLevel) &#123;</span><br><span class="line">            <span class="comment">// 把新增节点插入q和r之间</span></span><br><span class="line">            <span class="keyword">if</span> (!q.link(r, t))</span><br><span class="line">                <span class="keyword">break</span>; <span class="comment">// restart</span></span><br><span class="line">            <span class="comment">// t节点的值为空，需要删除</span></span><br><span class="line">            <span class="keyword">if</span> (t.node.value == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">// 利用findNode函数的副作用，清除已删除的节点</span></span><br><span class="line">                findNode(key);</span><br><span class="line">                <span class="keyword">break</span> splice;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 到达最底层，插入完毕，退出循环</span></span><br><span class="line">            <span class="keyword">if</span> (--insertionLevel == <span class="number">0</span>)</span><br><span class="line">                <span class="keyword">break</span> splice;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 上面节点已经插入完毕了，插入下一个节点，移动到下一层level</span></span><br><span class="line">        <span class="keyword">if</span> (--j &gt;= insertionLevel &amp;&amp; j &lt; level)</span><br><span class="line">            t = t.down;</span><br><span class="line">        q = q.down;</span><br><span class="line">        r = q.right;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这段源码主要是有两步，一是找到相应层次的该节点插入的位置，第二部分在该位置插入，然后下移。</p>
<p>到这里put操作就结束了，代码量还是很多的，理解了就行，稍微总结下。</p>
<p>1.先通过findPredecessor()方法找到前辈节点Node，这个过程会通过unlink()方法删除一些已经被标记的节点。<br>2.找到前辈节点后，新建Node节点插入到原始数据链表中。<br>3.随机生成一个数，判定是否需要添加该跳表的层级，并生成插入Node的Index和HeadIndex。<br>4.将生成的Index链表插入到跳表结构中。</p>
<h2 id="get操作"><a href="#get操作" class="headerlink" title="get操作"></a>get操作</h2><p>看源码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> V <span class="title">doGet</span><span class="params">(Object key)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (key == <span class="keyword">null</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">    Comparator&lt;? <span class="keyword">super</span> K&gt; cmp = comparator;</span><br><span class="line">    outer: <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">        <span class="keyword">for</span> (Node&lt;K,V&gt; b = findPredecessor(key, cmp), n = b.next;;) &#123;</span><br><span class="line">            Object v; <span class="keyword">int</span> c;</span><br><span class="line">            <span class="keyword">if</span> (n == <span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">break</span> outer;</span><br><span class="line">            Node&lt;K,V&gt; f = n.next;</span><br><span class="line">            <span class="keyword">if</span> (n != b.next)                <span class="comment">// inconsistent read</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">if</span> ((v = n.value) == <span class="keyword">null</span>) &#123;    <span class="comment">// n is deleted</span></span><br><span class="line">                n.helpDelete(b, f);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (b.value == <span class="keyword">null</span> || v == n)  <span class="comment">// b is deleted</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">if</span> ((c = cpr(cmp, key, n.key)) == <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>) V vv = (V)v;</span><br><span class="line">                <span class="keyword">return</span> vv;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (c &lt; <span class="number">0</span>)</span><br><span class="line">                <span class="keyword">break</span> outer;</span><br><span class="line">            b = n;</span><br><span class="line">            n = f;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>代码量直接比put操作少三分之二了，简单了很多，过程就和doPut操作的第一步差不多。</p>
<p>通过findPredecessor()方法找到前辈节点，然后从前驱结点开始往后查找，找到与key相等的结点，则返回该结点，否则，返回null。在这个过程中会删除一些已经标记为删除状态的结点。</p>
<h2 id="remove操作"><a href="#remove操作" class="headerlink" title="remove操作"></a>remove操作</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> V <span class="title">doRemove</span><span class="params">(Object key, Object value)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (key == <span class="keyword">null</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line">    Comparator&lt;? <span class="keyword">super</span> K&gt; cmp = comparator;</span><br><span class="line">    outer: <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">        <span class="comment">// 找到给定key节点的前辈节点</span></span><br><span class="line">        <span class="keyword">for</span> (Node&lt;K,V&gt; b = findPredecessor(key, cmp), n = b.next;;) &#123;</span><br><span class="line">            Object v; <span class="keyword">int</span> c;</span><br><span class="line">            <span class="keyword">if</span> (n == <span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">break</span> outer;</span><br><span class="line">            Node&lt;K,V&gt; f = n.next;</span><br><span class="line">            <span class="comment">// 不一致读，重新开始</span></span><br><span class="line">            <span class="keyword">if</span> (n != b.next)                    <span class="comment">// inconsistent read</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">if</span> ((v = n.value) == <span class="keyword">null</span>) &#123;        <span class="comment">// n is deleted</span></span><br><span class="line">                <span class="comment">// 帮助清除已删除节点</span></span><br><span class="line">                n.helpDelete(b, f);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// b节点已删除</span></span><br><span class="line">            <span class="keyword">if</span> (b.value == <span class="keyword">null</span> || v == n)      <span class="comment">// b is deleted</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="comment">// key小于当前结点的key，跳出循环</span></span><br><span class="line">            <span class="keyword">if</span> ((c = cpr(cmp, key, n.key)) &lt; <span class="number">0</span>)</span><br><span class="line">                <span class="keyword">break</span> outer;</span><br><span class="line">            <span class="comment">// key大于当前结点的key，后移</span></span><br><span class="line">            <span class="keyword">if</span> (c &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                b = n;</span><br><span class="line">                n = f;</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 找到节点</span></span><br><span class="line">            <span class="comment">// value != null 表示需要同时校验key-value值</span></span><br><span class="line">            <span class="keyword">if</span> (value != <span class="keyword">null</span> &amp;&amp; !value.equals(v))</span><br><span class="line">                <span class="keyword">break</span> outer;</span><br><span class="line">            <span class="comment">// CAS替换value为null</span></span><br><span class="line">            <span class="keyword">if</span> (!n.casValue(v, <span class="keyword">null</span>))</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="comment">// 给节点添加删除标识（next节点改为一个指向自身的节点）</span></span><br><span class="line">            <span class="comment">// 然后把前辈节点的next节点CAS修改为next.next节点（彻底解除n节点的链接）</span></span><br><span class="line">            <span class="keyword">if</span> (!n.appendMarker(f) || !b.casNext(n, f))</span><br><span class="line">                <span class="comment">// 如果CAS失败，清除已删除的节点后重新循环</span></span><br><span class="line">                findNode(key);                  <span class="comment">// retry via findNode</span></span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// 清理节点</span></span><br><span class="line">                findPredecessor(key, cmp);      <span class="comment">// clean index</span></span><br><span class="line">                <span class="keyword">if</span> (head.right == <span class="keyword">null</span>)</span><br><span class="line">                    <span class="comment">// 减少跳表层级</span></span><br><span class="line">                    tryReduceLevel();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 返回对应value</span></span><br><span class="line">            <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>) V vv = (V)v;</span><br><span class="line">            <span class="keyword">return</span> vv;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>doRemove操作和get差不多，找到需要删除节点的前辈节点，如果在查找过程中发现有已经删除的节点，就帮助清除节点。找到后不会直接删除，先利用 CAS 给这个节点添加一个删除标识（next 节点改为一个指向自身的节点），然后再利用 CAS 解除它的链接；如果途中 CAS 执行失败，则调用findNode方法来清除已经删除的节点。</p>
<p>最后检查该节点是不是这层唯一的index，如果是的话，调用tryReduceLevel()方法把这层干掉，完成删除。</p>
<p>从remove源码可以看出，remove方法仅仅是把Node的value设置null，并没有真正删除该节点Node，其实从上面的put操作、get操作我们可以看出，他们在寻找节点的时候都会判断节点的value是否为null，如果为null，则调用unLink()方法取消关联关系，完成删除操作。</p>
<h2 id="tryReduceLevel降级操作"><a href="#tryReduceLevel降级操作" class="headerlink" title="tryReduceLevel降级操作"></a>tryReduceLevel降级操作</h2><p>remove里面的删除层级操作。</p>
<p>如果最高的前三个HeadIndex不为空，并且其right域都为null，那么就将level减少1层，并将head设置为之前head的下一层，设置完成后，还有检测之前的head的right域是否为null，如果为null，则减少层级成功，否则再次将head设置为h。</p>
<p>h.level &gt; 3代表跳表只有在层级大于3时才可以降级。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">tryReduceLevel</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    HeadIndex&lt;K,V&gt; h = head;</span><br><span class="line">    HeadIndex&lt;K,V&gt; d;</span><br><span class="line">    HeadIndex&lt;K,V&gt; e;</span><br><span class="line">    <span class="keyword">if</span> (h.level &gt; <span class="number">3</span> &amp;&amp;</span><br><span class="line">        (d = (HeadIndex&lt;K,V&gt;)h.down) != <span class="keyword">null</span> &amp;&amp;</span><br><span class="line">        (e = (HeadIndex&lt;K,V&gt;)d.down) != <span class="keyword">null</span> &amp;&amp;</span><br><span class="line">        e.right == <span class="keyword">null</span> &amp;&amp;</span><br><span class="line">        d.right == <span class="keyword">null</span> &amp;&amp;</span><br><span class="line">        h.right == <span class="keyword">null</span> &amp;&amp;</span><br><span class="line">        casHead(h, d) &amp;&amp; <span class="comment">// try to set</span></span><br><span class="line">        h.right != <span class="keyword">null</span>) <span class="comment">// recheck</span></span><br><span class="line">        casHead(d, h);   <span class="comment">// try to backout</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>OK，这篇文章到此也就结束了，ConcurrentSkipListMap过程不算复杂，重要的还是理解。</p>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>如果你觉得这篇文章对你有用，欢迎赞赏哦~</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/wechatpay.png" alt="Felix 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/alipay.png" alt="Felix 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
	
	<div>
  
    <div>
    
        <div style="text-align: center;font-size: 13px;letter-spacing: 10px;user-select: none;margin-top: 50px;color: #bbb;">本文结束啦 <i class="fa fa-star"></i> 感谢您阅读</div>
    
</div>
  
</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"><i class="fa fa-tag"></i> java</a>
          
            <a href="/tags/JUC/" rel="tag"><i class="fa fa-tag"></i> JUC</a>
          
            <a href="/tags/ConcurrentSkipListMap/" rel="tag"><i class="fa fa-tag"></i> ConcurrentSkipListMap</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div class="social_share">
            
            
               <div id="needsharebutton-postbottom">
                 <span class="btn" title="分享">
                    <i class="fa fa-share-alt" aria-hidden="true"></i>
                 </span>
               </div>
            
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
			
			   <a href="/2019/04/19/记一次面经/" rel="prev" title="记一次面经">
			   <i class="fa fa-chevron-left"></i> 记一次面经
			   
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
             
				<a href="/2019/01/14/跳表-SkipList-了解下？/" rel="next" title="跳表(SkipList)了解下？">
				跳表(SkipList)了解下？ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zODUyNC8xNTA1Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
			<a href="/">
              <img class="site-author-image" itemprop="image"
                src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/user_head_img.jpg"
                alt="Felix" />
				</a>
            
              <p class="site-author-name" itemprop="name">Felix</p>
              <p class="site-description motion-element" itemprop="description">周宇峰的博客</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">94</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">16</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">88</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/542869246" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/zyf542869246" target="_blank" title="Gitee"><i class="fa fa-fw fa-git"></i>Gitee</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://music.163.com/#/user/home?id=343583524" target="_blank" title="网易云音乐"><i class="fa fa-fw fa-music"></i>网易云音乐</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/yu-sui-58/activities" target="_blank" title="知乎"><i class="fa fa-fw fa-globe"></i>知乎</a>
                  
                </span>
              
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://zblog.dawnings.top/" title="删库东😎" target="_blank">删库东😎</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://ntssl.cn" title="ntssl.cn" target="_blank">ntssl.cn</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.imyzt.top/" title="imyzt" target="_blank">imyzt</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.charmsongo.cn/" title="charmsongo" target="_blank">charmsongo</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.52share.online" title="HuiProgramer" target="_blank">HuiProgramer</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://music.163.com/#/user/home?id=343583524" title="😆 网易云音乐 😆" target="_blank">😆 网易云音乐 😆</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.zhihu.com/people/yu-sui-58/activities" title="😤 知乎 😤" target="_blank">😤 知乎 😤</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ityouknow.com/spring-boot.html" title="spring-boot 纯洁的微笑" target="_blank">spring-boot 纯洁的微笑</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000" title="Python教程 廖雪峰" target="_blank">Python教程 廖雪峰</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="/about" title="关于此博客" target="_blank">关于此博客</a>
                  </li>
                
              </ul>
			  <div id="days"></div>
<script>
function show_date_time(){
window.setTimeout("show_date_time()", 1000);
BirthDay=new Date("07/30/2018 15:13:14");
today=new Date();
timeold=(today.getTime()-BirthDay.getTime());
sectimeold=timeold/1000
secondsold=Math.floor(sectimeold);
msPerDay=24*60*60*1000
e_daysold=timeold/msPerDay
daysold=Math.floor(e_daysold);
e_hrsold=(e_daysold-daysold)*24;
hrsold=setzero(Math.floor(e_hrsold));
e_minsold=(e_hrsold-hrsold)*60;
minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
seconds=setzero(Math.floor((e_minsold-minsold)*60));
document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
if (i<10)
{i="0" + i};
return i;
}
show_date_time();
</script>
            </div>
          

          
            
          
          <div id="days"></div>
<script>
function show_date_time(){
window.setTimeout("show_date_time()", 1000);
BirthDay=new Date("07/30/2018 15:13:14");
today=new Date();
timeold=(today.getTime()-BirthDay.getTime());
sectimeold=timeold/1000
secondsold=Math.floor(sectimeold);
msPerDay=24*60*60*1000
e_daysold=timeold/msPerDay
daysold=Math.floor(e_daysold);
e_hrsold=(e_daysold-daysold)*24;
hrsold=setzero(Math.floor(e_hrsold));
e_minsold=(e_hrsold-hrsold)*60;
minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
seconds=setzero(Math.floor((e_minsold-minsold)*60));
document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
if (i<10)
{i="0" + i};
return i;
}
show_date_time();
</script>
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#回顾"><span class="nav-number">1.</span> <span class="nav-text">回顾</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ConcurrentSkipListMap数据结构"><span class="nav-number">2.</span> <span class="nav-text">ConcurrentSkipListMap数据结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重要的内部类"><span class="nav-number">3.</span> <span class="nav-text">重要的内部类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Index"><span class="nav-number">3.1.</span> <span class="nav-text">Index</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#HeadIndex"><span class="nav-number">3.2.</span> <span class="nav-text">HeadIndex</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Node"><span class="nav-number">3.3.</span> <span class="nav-text">Node</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#属性"><span class="nav-number">4.</span> <span class="nav-text">属性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#构造函数"><span class="nav-number">5.</span> <span class="nav-text">构造函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#put操作"><span class="nav-number">6.</span> <span class="nav-text">put操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#get操作"><span class="nav-number">7.</span> <span class="nav-text">get操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#remove操作"><span class="nav-number">8.</span> <span class="nav-text">remove操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#tryReduceLevel降级操作"><span class="nav-number">9.</span> <span class="nav-text">tryReduceLevel降级操作</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-tint"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Felix</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">站点总字数：</span>
    
    <span title="站点总字数">538k</span>
  

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    
    <span title="站点阅读时长">11:13</span>
  
  
  <div style="background-image:linear-gradient(90deg,#6dba82 0,#07b39b 15%,#1098ad 30%,#5073b8 44%,#a166ab 58%,#ef4e7b 72%,#f37055 86%,#f79533 100%);background-size:cover;-webkit-background-clip:text;-webkit-text-fill-color:transparent;user-select:none"><i>Tip: 本站电脑访问体验更佳耶&nbsp;<i class="fa fa-angellist" style="display:inline"></i></i></div>
  
</div>


<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>





-->



  <span>Hosted by <a href="https://pages.coding.me" >Coding Pages</a></span>



<div class="weixin-box">
  <div class="weixin-menu">
    <div class="weixin-hover">
      <div class="weixin-description">微信扫一扫，加好友</div>
    </div>
  </div>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  















  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.1"></script>



  



  
    <script type="text/javascript">
      window.livereOptions = {
        refer: '2019/01/17/剑指ConcurrentSkipListMap/'
      };
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  









  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script>
    
    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function ({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text(counter.time + 1);
            
            Counter('put', `/classes/Counter/${counter.objectId}`, JSON.stringify({ time: { "__op":"Increment", "amount":1 } }))
            
            .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
            })
          } else {
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text('Counter not initialized! See more at console err msg.');
              console.error('ATTENTION! LeanCloud counter has security bug, see here how to solve it: https://github.com/theme-next/hexo-leancloud-counter-security. \n But you also can use LeanCloud without security, by set \'security\' option to \'false\'.');
            
          }
        })
      .fail(function ({ responseJSON }) {
        console.log('LeanCloud Counter Error:' + responseJSON.code + " " + responseJSON.error);
      });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + "4DkhRkq5CadWFisToA3zFrop-gzGzoHsz")
        .done(function ({ api_server }) {
          var Counter = function (method, url, data) {
            return $.ajax({
              method: method,
              url: `https://${api_server}/1.1${url}`,
              headers: {
                'X-LC-Id': "4DkhRkq5CadWFisToA3zFrop-gzGzoHsz",
                'X-LC-Key': "xihAA2ETGTdekJFloguCmmgq",
                'Content-Type': 'application/json',
              },
              data: data,
            });
          };
          
          addCount(Counter);
          
        })
    });
  </script>



  

  

  

  
  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Linkedin,Mailto,Reddit,Delicious,StumbleUpon,Pinterest,Facebook,GooglePlus,Slashdot,Technorati,Posterous,Tumblr,GoogleBookmarks,Newsvine,Evernote,Friendfeed,Vkontakte,Odnoklassniki,Mailru";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "default";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Linkedin,Mailto,Facebook,Tumblr,Friendfeed";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  

  

  

  

  
  <div class="bg_content">
	<canvas id="canvas"></canvas>
	<canvas id="canvas1"></canvas>
	  <!-- html5-canvas-animation
	  <div class="canvas-wrap">
		<div id="canvas3" class="gradient"></div>
	</div>-->
  </div>
  
  
  
  <!-- 右上角github关注-->
  <div class="forkme">
	<!--<a href="https://github.com/542869246">
	<img style="position: absolute; top: 0; right: 0; border: 0;" src="http://pd2tflnys.bkt.clouddn.com/img/blog/forkme_right_red_aa0000.png" alt="Fork me on GitHub">
	</a>-->
	<a href="https://github.com/542869246" class="github-corner" aria-label="View source on GitHub">
	<svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true">
	<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
	<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path>
	</svg>
	</a>
	<style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
  </div>
  
  <!-- 音乐播放器-->
  <link rel="stylesheet" href="/dist/APlayer.min.css">
  <div id="aplayer"></div>
  <script type="text/javascript" src="/dist/APlayer.min.js"></script>
  <script type="text/javascript" src="/dist/music.js"></script>
 
   <!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
 <!-- 页面点击汉字 -->
<script type="text/javascript" src="/js/src/hanzi.js"></script>
  
  <!-- 代码块复制功能 -->
<script type="text/javascript" src="/js/src/clipboard.min.js"></script>  
<script type="text/javascript" src="/js/src/clipboard-use.js"></script>
<!-- 流星雨-->
<!--<script type="text/javascript" src="/js/src/meteor-rain.js"></script>-->
<!-- 粒子效果-->
<script type="text/javascript" src="/js/src/dynamic_bg.js"></script>

<!-- html5-canvas-animation-->
<!-- Main library
<script src="/js/src/three.min.js"></script> -->
<!-- Helpers
<script src="/js/src/projector.js"></script>
<script src="/js/src/canvas-renderer.js"></script> -->
<!-- Visualitzation adjustments 
<script src="/js/src/3d-lines-animation.js"></script>-->
<!-- Animated background color 
<script src="/js/src/color.js"></script>-->



</body>
</html>
